import ResizeObserver from 'resize-observer-polyfill'
import { useEffect, useRef } from 'preact/hooks'
import { IEVersion } from '@/utils/index'

const IE8Lte = IEVersion && IEVersion <= 8

export function useResize(callback: () => void, el: HTMLElement | null) {
  const savedCallback = useRef(callback)

  useEffect(() => {
    savedCallback.current = callback
  })

  const observerRef = useRef<ResizeObserver | null>(null)

  useEffect(() => {
    if (!el) {
      return
    }
    if (IE8Lte) {
      function resize() {
        savedCallback.current()
      }
      el.addEventListener('resize', resize)
      let hasRemoved = false
      setTimeout(function () {
        if (!hasRemoved) {
          savedCallback.current()
        }
      }, 17)
      return () => {
        hasRemoved = true
        el.removeEventListener('resize', resize)
      }
    }
    if (!observerRef.current) {
      observerRef.current = new ResizeObserver(() => {
        savedCallback.current()
      })
    }
    const observer = observerRef.current
    observer.observe(el)
    return () => observer.disconnect()
  }, [el])
}
